using UnityEngine;

namespace MyTools{
public class ParabolicMotion3D
{
    private Vector3 startPoint;
    private Vector3 endPoint;
    private float totalTravelTime;
    private float horizontalSpeed;
    private float initialVerticalVelocity;
    private const float gravity = 9.81f; // 重力加速度 m/s^2

    // 构造函数，初始化抛物线参数
    public ParabolicMotion3D(Vector3 start, Vector3 end, float totalTime)
    {
        startPoint = start;
        endPoint = end;
        totalTravelTime = totalTime;
        CalculateMotionParameters();
    }

    // 计算水平和垂直运动参数
    private void CalculateMotionParameters()
    {
        // 水平距离
        Vector2 horizontalStart = new Vector2(startPoint.x, startPoint.y);
        Vector2 horizontalEnd = new Vector2(endPoint.x, endPoint.y);
        float horizontalDistance = Vector2.Distance(horizontalStart, horizontalEnd);

        // 水平速度
        horizontalSpeed = horizontalDistance / totalTravelTime;

        // 垂直运动参数
        float verticalDisplacement = endPoint.z - startPoint.z;
        initialVerticalVelocity = (verticalDisplacement + 0.5f * gravity * totalTravelTime * totalTravelTime) / totalTravelTime;
    }

    // 根据当前时间返回位置和切线方向
    public (Vector3 position, Vector3 tangent) GetPositionAndTangentAtTime(float currentTime)
    {
        if (currentTime > totalTravelTime)
        {
            currentTime = totalTravelTime; // 防止超出时间范围
        }

        // 计算当前水平位置
        float horizontalX = Mathf.Lerp(startPoint.x, endPoint.x, currentTime / totalTravelTime);
        float horizontalY = Mathf.Lerp(startPoint.y, endPoint.y, currentTime / totalTravelTime);
        
        // 计算当前垂直位置
        float currentVerticalPosition = startPoint.z + initialVerticalVelocity * currentTime - 0.5f * gravity * currentTime * currentTime;

        // 组合位置向量
        Vector3 position = new Vector3(horizontalX, horizontalY, currentVerticalPosition);

        // 计算切线向量
        Vector3 tangent = new Vector3(endPoint.x - startPoint.x, endPoint.y - startPoint.y, initialVerticalVelocity - gravity * currentTime).normalized;

        return (position, tangent);
    }
}
}